package csharp.cauth;

import java.io.File;
import java.net.MalformedURLException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;

import org.bukkit.Location;

import com.alta189.sqlLibrary.MySQL.mysqlCore;

import csharp.cauth.properties.PlayerProp;
import csharp.cauth.utils.Log;
import csharp.cauth.utils.SLAPI;

/**
 * 
 * @author Ярослав (CSharp) Class for players saving/loading.
 */
public class PlayersSL
{
	private static mysqlCore manageMySQL = CAuth.manageMySQL;

	/**
	 * Saving players to file. Using SLAPI from bukkit wiki, thanks to Tomsik68.
	 */
	public static void savePlayers()
	{
		if (PluginConfig.useMySQL)
			saveToMySQL();
		else
			saveToFile();

		Log.log(Level.INFO, "Players saved.");
	}

	private static void saveToMySQL()
	{
		// TODO Auto-generated method stub

	}

	private static void saveToFile()
	{
		try
		{
			SLAPI.save(CAuth.players, CAuth.mainDir + File.separator
					+ "players.bin");
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
	}

	public static void loadPlayers()
	{
		if (PluginConfig.useMySQL)
			loadFromMySQL();
		else
			loadFromFile();

		Log.log(Level.INFO, "Players loaded.");
	}

	/**
	 * Loading players from file. Using SLAPI from bukkit wiki, thanks to
	 * Tomsik68.
	 */
	private static void loadFromFile()
	{
		try
		{
			ArrayList<PlayerProp> load = (ArrayList<PlayerProp>) SLAPI
					.load(CAuth.mainDir + File.separator + "players.bin");

			CAuth.players = load;

			for (PlayerProp player : load)
			{
				String ip = player.getIp();

				if (!CAuth.ipCounter.containsKey(ip))
				{
					CAuth.ipCounter.put(ip, 1);
				}
				else
				{
					Integer count = CAuth.ipCounter.get(ip);

					CAuth.ipCounter.put(ip, count + 1);
				}
			}
		}
		catch (Exception e)
		{
			// e.printStackTrace();
		}
	}

	private static void loadFromMySQL()
	{
		try
		{
			ResultSet result = manageMySQL.sqlQuery("SELECT * FROM users");

			if (result != null)
			{
				try
				{
					while (result.next())
					{
						String ip = result.getString("ip");
						PlayerProp temp;

						try
						{
							temp = new PlayerProp(
									result.getInt("id"),
									result.getString("login"),
									result.getString("password"),
									ip,
									new Location(
											CAuth.instance
													.getServer()
													.getWorld(
															result.getString("world")),
											result.getInt("x"), result
													.getInt("y"), result
													.getInt("z")));

							temp.setRegistred(result.getDate("registered"));
							temp.setLastLogin(result.getDate("lastlogin"));
						}
						catch (Exception e)
						{
							Log.log(Level.WARNING, "Can't load user with id "
									+ result.getInt("id") + ".");

							continue;
						}

						CAuth.players.add(temp);

						if (!CAuth.ipCounter.containsKey(ip))
						{
							CAuth.ipCounter.put(ip, 1);
						}
						else
						{
							Integer count = CAuth.ipCounter.get(ip);

							CAuth.ipCounter.put(ip, count + 1);
						}
					}
				}
				catch (SQLException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InstantiationException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * MySQL functions.
	 */

	/**
	 * Update player location (for MySQL).
	 * 
	 * @param id
	 * @param lastLoc
	 */
	public static void updateLocation(Integer id, Location lastLoc)
	{
		try
		{
			manageMySQL.updateQuery("UPDATE users SET x = " + lastLoc.getX()
					+ ", y = " + lastLoc.getY() + ", z = " + lastLoc.getZ()
					+ ", world = '" + lastLoc.getWorld().getName()
					+ "' WHERE id = " + id);
		}
		catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InstantiationException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Remove player (for MySQL).
	 * 
	 * @param id
	 */
	public static void remove(Integer id)
	{
		try
		{
			manageMySQL.deleteQuery("DELETE FROM users WHERE id = " + id);
		}
		catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InstantiationException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Update password (for MySQL).
	 * 
	 * @param id
	 * @param pass
	 */
	public static void updatePassword(Integer id, String pass)
	{
		try
		{
			manageMySQL.updateQuery("UPDATE users SET password = '" + pass
					+ "' WHERE id = " + id);
		}
		catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InstantiationException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Update last login (for MySQL).
	 * 
	 * @param id
	 */
	public static void updateLastLogin(Integer id)
	{
		try
		{
			manageMySQL
					.updateQuery("UPDATE users SET lastlogin = NOW() WHERE id = "
							+ id);
		}
		catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InstantiationException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Integer create(String login, String password, String ip)
	{
		try
		{
			return manageMySQL
					.insertQuery("INSERT INTO users (`login`, `password`, `ip`) VALUES ('"
							+ login + "', '" + password + "', '" + ip + "')");
		}
		catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (InstantiationException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
}
